package com.ld.task;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁的使用
 */
public class UseReadWriteLock {

    ReadWriteLock lock = new ReentrantReadWriteLock();
    Lock readLock = lock.readLock();
    Lock writeLock = lock.writeLock();
    int num = 0;

    public void setNum(int num) {
        writeLock.lock();
        try {
            this.num = num;
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public int getNum() {
        readLock.lock();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
        return this.num;
    }

    public static void main(String[] args) throws InterruptedException {
        UseReadWriteLock useReadWriteLock = new UseReadWriteLock();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    int num = new Random().nextInt();
                    useReadWriteLock.setNum(num);
                    long endTime = System.currentTimeMillis();
                    System.out.println(Thread.currentThread().getName() + "写" + num + "耗时" + (endTime - startTime));
                }
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    int num = useReadWriteLock.getNum();
                    long endTime = System.currentTimeMillis();
                    System.out.println(Thread.currentThread().getName() + "读取num耗时" + (endTime - startTime) + "ms,读取的值为" + num);
                }
            }).start();
        }



    }
}
